package com.ld.blecardlibrarydes.ble;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.ld.blecardlibrarydes.utils.CommonUtil;
import com.ld.blecardlibrarydes.utils.DesUtil;
import com.ld.blecardlibrarydes.utils.ToastUtil;

/**
 * Created by lirongkun on 16/10/9.
 */
public class BLEUtil {

    private BluetoothLeService mBluetoothLeService;
    private Context context;
    private BluetoothAdapter mBluetoothAdapter;
    private Handler mHandler;
    private String DeviceName;
    private BleDataListener bleDataListener;
    private byte[] NormalData;
    private int CountNum;
    private byte ErrorData;
    private byte[] DataSended;

    /**
     *
     * @param context 上下文
     * @param bleDataListener 数据回调
     */
    public BLEUtil(Context context,BleDataListener bleDataListener){
        this.context = context;
        this.bleDataListener = bleDataListener;
        init();
    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    bleDataListener.Disconnected();
                    break;
                case 1:
                    bleDataListener.Connected();
                    break;
                case 2:
                    bleDataListener.NormalData(NormalData,CountNum);
                    break;
                case 3:
                    bleDataListener.ErrorData(ErrorData);
                    break;
                case 4:
                    bleDataListener.SendData(DataSended);
                    break;
                default:
                    break;
            }
        }
    };
    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
            mBluetoothLeService.setDataChangeListener(new BluetoothLeService.DataChangeListener() {
                @Override
                public void Disconnected() {
                    handler.sendEmptyMessage(0);
                }

                @Override
                public void Connected() {
                    handler.sendEmptyMessage(1);
                }

                @Override
                public void NormalData(byte[] data,int count) {
                    NormalData = data;
                    CountNum = count;
                    handler.sendEmptyMessage(2);
                }

                @Override
                public void ErrorData(byte errorData) {
                    ErrorData = errorData;
                    handler.sendEmptyMessage(3);
                }

                @Override
                public void SendData(byte[] sendData) {
                    DataSended = sendData;
                    handler.sendEmptyMessage(4);
                }
            });
        }
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };
    //初始化
    public void init(){
        mHandler = new Handler();
        final BluetoothManager bluetoothManager =
                (BluetoothManager)context.getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        if(!BleInit(mBluetoothAdapter)){
            ToastUtil.toastShort(context, "蓝牙不支持");
            return;
        }

        if(!mBluetoothAdapter.isEnabled()){
            CommonUtil.showInfoDialog(context, "请求打开蓝牙", null,"确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mBluetoothAdapter.enable();
                }
            });
        }

        Intent gattServiceIntent = new Intent(context, BluetoothLeService.class);
        context.bindService(gattServiceIntent, mServiceConnection, context.BIND_AUTO_CREATE);//绑定服务
    }


    private boolean BleInit( BluetoothAdapter myBluetoothAdapter){
        Intent gattServiceIntent = new Intent(context, BluetoothLeService.class);

        context.bindService(gattServiceIntent, mServiceConnection,context.BIND_AUTO_CREATE);

        if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            ToastUtil.toastShort(context, "蓝牙不支持");
            return false;
        }
        if(myBluetoothAdapter == null){
            ToastUtil.toastShort(context, "蓝牙不支持");
            return false;
        }
        return true;
    }

    /**
     * 蓝牙扫描
     * @param listener 处理扫描失败任务
     */
    public void ConnectDev(final ScanListener listener) {
            // 扫描六秒钟
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
//                  mBluetoothLeService.broadcastUpdate(mBluetoothLeService.ACTION_GATT_DISCONNECTED);
                    listener.Fail();

                }
            }, 6000);
            mBluetoothAdapter.startLeScan(mLeScanCallback);
    }
    // 蓝牙扫描,自动连接
    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {

                @Override
                public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
                    String mDeviceAddress = device.getAddress();
                    if (device.getName() == null) return;
                    if (device.getName().contains("LKT BLE")&&mDeviceAddress!=null){
//                        若扫描到蓝牙硬件，停止扫描并连接
                        mBluetoothAdapter.stopLeScan(mLeScanCallback);
                        if (!mBluetoothLeService.initialize()) {
                            ToastUtil.toastShort(context,"Unable to initialize Bluetooth");
                            return;
                        }
                        ToastUtil.toastShort(context,"正在连接蓝牙卡片");
                        mBluetoothLeService.connect(mDeviceAddress);
                    }
                }
            };
    //断开蓝牙
    public void Disconnect(){
        if (mBluetoothLeService != null)
            mBluetoothLeService.disconnect();
    }

    /**
     *
     * @param function 功能号
     */
//    public void ExchangeAPDU(int function, byte[] Senddata){
//        if (mBluetoothLeService != null)
//            mBluetoothLeService.writeData(function,Senddata);
//    }

    public static byte[] Generate_APDU(int function,byte[] data){
        return NfcbleModel.Generate_APDU(function,data);
    }

    public void ExchangeAPDU(byte[] Senddata){
        if (mBluetoothLeService != null)
            mBluetoothLeService.writeData(Senddata);
    }

    public void setMasterKey(String key){
        DesUtil.setMasterKey(key);
    }


    //关闭蓝牙服务
    public void Destroy(){
        mBluetoothLeService.close();
        context.unbindService(mServiceConnection);
        mBluetoothLeService = null;
    }
}
